<template>
  <el-dialog
    title="代码预览"
    :visible.sync="showCode"
    width="60%"
    height="600px"
  >
    <codeMirror
      :str="code"
      :echartsStr="echartsCode"
      @switch="switchCodeMirror"
      ref="codeMirror"
    >
    </codeMirror>
    <div slot="footer" class="dialog-footer">
      <el-button @click="showCode = false">取 消</el-button>
      <el-button type="primary" @click="copyCode">复制代码</el-button>
    </div>
  </el-dialog>
</template>

<script>
import codeMirror from "@/components/CodeMirror/index";
import ClipboardJS from "clipboard";
import common from "../common";
export default {
  name: "PreiviewDialog",
  mixins: [common],
  components: {
    codeMirror,
  },
  props: {},
  data() {
    return {
      echartsCode: "",
      copyFlag: "first",
      code: "",
      showCode: false,
    };
  },
  mounted() {},
  methods: {
    // 预览代码
    showDialog() {
      this.showCode = true;
      const codeStr = this.generateCode();
      const echartCodeStr = this.generateEchartsCode();
      this.code = codeStr;
      this.echartsCode = echartCodeStr;
    },
    switchCodeMirror(val) {
      this.copyFlag = val;
    },
    handleClose() {
      this.showCode = false;
      this.code = "";
    },
    copyCode() {
      const clipboard = new ClipboardJS("#copyNode", {
        text: (trigger) => {
          let copyFlag = this.copyFlag;
          const codeStr =
            copyFlag === "first"
              ? this.$refs["codeMirror"].code
              : this.$refs["codeMirror"].echartsCode;
          this.$notify({
            title: "成功",
            message: "代码已复制到剪切板，可粘贴。",
            type: "success",
          });
          return codeStr;
        },
      });
      clipboard.on("error", (e) => {
        this.$message.error("代码复制失败");
      });
      document.getElementById("copyNode").click();
    },
  },
};
</script>

<style scoped>
</style>